package com.cnoc.base.json;

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class GsonUtils {
	private static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
//	private static Gson gson = new GsonBuilder().setDateFormat(DEFAULT_DATE_FORMAT).create();

	private static Gson gson = new GsonBuilder().  
            registerTypeAdapter(Double.class, new JsonSerializer<Double>() {  

                @Override  
                public JsonElement serialize(Double src, Type typeOfSrc, JsonSerializationContext context) {  
                    if (src == src.longValue())  
                        return new JsonPrimitive(src.longValue());  
                    return new JsonPrimitive(src);  
                }  
            }).create();

	public static String toJson(Object object) {
		return gson.toJson(object);
	}

	public static <T> T toObject(String paramJson, Class<T> clazz) {
		return gson.fromJson(paramJson, clazz);
	}

	@SuppressWarnings("unchecked")
	public static <T> List<T> toObjects(String paramJson, Class<T> clazz) {
		return (List<T>) gson.fromJson(paramJson, clazz);
	}
	
	public static Map<String,Object> toMap(String paramJson){
		return gson.fromJson(paramJson, new TypeToken<Map<String, Object>>(){}.getType());
	}
	
	public static Map<String,Integer> toMapForInteger(String paramJson){
		return gson.fromJson(paramJson, new TypeToken<Map<String, Integer>>(){}.getType());
	}
	
	public static Map<String,String> toMapForString(String paramJson){
		return gson.fromJson(paramJson, new TypeToken<Map<String, String>>(){}.getType());
	}
	
	public static LinkedHashMap<String,Object> toLinkedHashMap(String paramJson){
		return gson.fromJson(paramJson, new TypeToken<LinkedHashMap<String, Object>>(){}.getType());
	}
}